#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
void printArraya(int* a, int length)
{
    printf("call printArraya\n");
    for (int i = 0; i < length; ++i)
    {
        printf("%d,", a[i]);
    }
    printf("\n");
}
void percolateDown(position h, int start, int length)
{
    elementType tmp;
    int father = start;
    int child = start;
    if (h == NULL || length == 1)
    {
        return;
    }
    tmp = *(h+start);
    // left son is 2 * i + 1 and i starts with 0
    for (father = start; (2*father + 1 < length); )
    {
        child = 2 * father + 1; 
        if(((child + 1) < length )&& (h[child + 1] < h[child]))
        {
            child = child  + 1;
        }
        if(h[child] >= tmp)
            break;
        h[father] = h[child];
        father = child;   
    }
    h[father] = tmp;

}
heap buildheap(position h, int length)
{
    for (int i = length/2; i >= 0; --i)
    {
        percolateDown(h, i, length);
    }
    return h;
}
elementType deleteMin(position h, int length)
{
    elementType number;
    number = h[0];
    h[0] = h[length - 1];
    h[length - 1] = number;
    percolateDown(h, 0 ,length - 1);
    return number;
} 